package cn.luischen.handler;

import cn.luischen.exception.BusinessException;
import cn.luischen.utils.APIResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*
    统一异常处理 ControllerAdvice 需要配合@ExceptionHandler() 来使用


 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(BusinessException.class);//添加日志

    @ExceptionHandler(value = BusinessException.class)//指定来处理的异常类
    @ResponseBody//返回json字符串

    public APIResponse businessException(Exception e){

        String msg = "请求错误";
        if (e instanceof BusinessException){
            msg = ((BusinessException) e).getErrorCode();//如果异常是自定义的就走自定义的异常
        }
        logger.error("find exception:e={}",e.getMessage());
        e.printStackTrace();
        return APIResponse.fail(msg);
    }


}
